/**
 * Project: lionbule-other
 * 
 * File Created at 2012-4-2
 * $Id$
 * 
 * Copyright 1999-2100 Alibaba.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.poi;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
 * DataModel.
 * 
 * @author LionBule 2012-4-2 上午10:02:28
 */
public class DataModel {

    public static void main(String[] args) throws Exception, IOException {
        String path = "d:/DATAMODEL.xlsx";

        Workbook wb = WorkbookFactory.create(new File(path));

        //buildRoot
        Sheet catalogSheet = wb.getSheetAt(0);
        List<Node> nodes = savePath(catalogSheet);

        //buildProperty
        saveProperty(wb, nodes);
    }

    static Map<String, Integer> buildIntactPath(List<Node> nodes) {
        Map<String, Integer> lefves = new HashMap<String, Integer>();

        for (Node n : nodes) {
            int id = n.getId();
            if (id == -1)
                continue;

            StringBuilder sbIntactPath = new StringBuilder();
            sbIntactPath.append(n.getName());
            Node parentNode = n.getParent();
            while (parentNode != null && parentNode.getCode() != null) {
                sbIntactPath.insert(0, ".").insert(0, parentNode.getName());
                parentNode = parentNode.getParent();
            }

            if (n.isLeaf()) {
                String intactPath = sbIntactPath.toString();
                lefves.put(intactPath, n.getId());
                //System.out.println(intactPath);
            }
        }

        return lefves;
    }

    static List<Node> savePath(Sheet catalogSheet) {
        BuildeCatalog bc = new BuildeCatalog(catalogSheet);
        List<Node> nodes = bc.build();

        List<String> sqls = new ArrayList<String>();
        for (Node n : nodes) {
            if (n.getId() == -1) {
                continue;
            }

            StringBuilder sb = new StringBuilder();
            sb.append(
                    "insert into agds_dm_path (id,pcode,pname,parent_id,descs,gmt_create,gmt_modified,operator) values (")
                    .append(n.getId()).append(", '").append(n.getCode()).append("', '")
                    .append(n.getName()).append("',").append(n.getPid()).append(", '")
                    .append(n.getDesc()).append("', now(), now(), 'admin')");

            String sql = sb.toString();
            sqls.add(sql);
        }

        buildIntactPath(nodes);

        Store store = new Store();
        try {
            //TODO db
            store.save(sqls);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return nodes;
    }

    static void saveProperty(Workbook wb, List<Node> nodes) {
        Map<String, Integer> pathIds = buildIntactPath(nodes);

        int sheetNum = wb.getNumberOfSheets();
        for (int i = 2; i < sheetNum; i++) {
            Sheet tempSheet = wb.getSheetAt(i);
            String tmpSheetName = tempSheet.getSheetName();
            //System.out.println(tmpSheetName);

            //test
            BuildProperty bp = new BuildProperty(tempSheet);

            List<PropertyDO> rsPro = bp.getAllProperty();

            Integer pid = pathIds.get(tmpSheetName);
            if (pid == null) {
                System.out.println("pathid no exist. tmpSheetName=" + tmpSheetName);
                //throw new RuntimeException("pathid no exist. tmpSheetName=" + tmpSheetName);
                continue;
            }
            saveProperty(rsPro, pid);
        }

    }

    static void saveProperty(List<PropertyDO> rsPro, int pid) {
        List<String> sqls = new ArrayList<String>();
        for (PropertyDO d : rsPro) {
            StringBuilder sb = new StringBuilder();
            sb.append("insert into agds_dm_property ")
                    .append("(path_id,pcode,pname,data_type,validator,status,descs,creater,operator,gmt_create,gmt_modified) ")
                    .append("values (").append(pid).append(", \"").append(d.getCode()).append("\",\"")
                    .append(d.getName()).append("\",").append(d.getType()).append(",\"")
                    .append(d.getValidValues()).append("\",").append(d.getStatus()).append(", \"")
                    .append(d.getDesc()).append("\", 'admin', 'admin', now(), now()").append(")");
            String sql = sb.toString();
            //System.out.println(sql);
            
            sqls.add(sql);
        }

        Store store = new Store();
        try {
            //TODO db
            store.save(sqls);
        } catch (Exception e) {
            System.out.println("[error] pid="+pid);
            e.printStackTrace();
        }
    }

}
